<?php

namespace Modules\Order\Services;

use Modules\Goods\Entities\Goods;
use Modules\Order\Entities\Order;
use Illuminate\Support\Facades\Auth;
use Modules\Goods\Entities\Sku;

class OrderService
{
  // 创建购物订单
  public function create(int $merchant_id, string $channel = null, string $postscript = null, array $goods = null)
  {
    // 创建订单
    $order = new Order;
    $order->sn = $this->sn();
    $order->user_id = Auth::id();
    $order->merchant_id = $merchant_id;
    $order->channel = $channel;
    $order->postscript = $postscript;
    $order->status = Order::STATUS_NEW;
    $order->save();

    // 保存订单中的商品
    if (!empty($goods))
      $order->goods()->createMany($goods);

    return $order;
  }

  // 生成订单号
  protected function sn()
  {
    // 订单流水号前缀
    $prefix = date('YmdHis');
    while (true) {
      // 随机生成 6 位的数字
      $sn = $prefix . str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
      // 判断是否已经存在
      if (!Order::where('sn', $sn)->exists()) {
        return $sn;
      }
    }
  }

  // 查询最新的商品信息，以防止商品价格变动等问题。
  public function refresh(array $goods)
  {
    $result = array();

    // 遍历每一件商品
    foreach ($goods as $item) {
      if (empty($item)) continue;

      // 查询最新的商品信息
      if (array_has($item, 'id')) {
        // TODO: 根据 channel 使用对应的类
        $current = Sku::find($item['id']);
        $current->goods_id = $item['id'];
        $current->quantity = $item['quantity'];
        $current->name = $current->name ?? $current->goods()->first()->name;
        array_push($result, $current->toArray());
      }

    }

    return $result;
  }

  /**
   * 根据状态查询订单数据.
   *
   * @param $status
   */
  public function getOrderByStatus($status=0)
  {
    $order = Order::where('user_id', Auth::id())
      ->with('goods')
      ->orderBy('created_at', 'desc')
      ->where(function ($query) use ($status) {
        if (isset($status) && $status != 0) {
          $query->where('status', $status);
        } 
      })->paginate(10);
    return $order;
  }
}
